package com.yanxu.stopthreads;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/7/21-2024
 * @Description: 没有阻塞的情况下，正确停止线程的方法
 */
public class RightWayStopThreadWithoutSleep {

    /* 线程并不能正确的停止 */
    /*public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                int num = 0;
                while (num <= Integer.MAX_VALUE / 2) {
                    if (num % 10000 == 0) {
                        System.out.println(num + "是10000的倍数");
                    }
                    num++;
                }
                System.out.println("任务运行结束了");
            }
        });

        thread.start();
        Thread.sleep(2000);
        thread.interrupt();  //通知子线程 thread 中断。
    }*/

    public static void main(String[] args) throws InterruptedException {
        final Thread thread = new Thread(new Runnable() {
            public void run() {
                int num = 0;
                while (num <= Integer.MAX_VALUE / 2  && !Thread.currentThread().isInterrupted()) {
                    if (num % 10000 == 0) {
                        System.out.println(num + "是10000的倍数");
                    }
                    num++;
                }
                System.out.println("任务运行结束了");
            }
        });

        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }
}